#import <MediaPlayer/MediaPlayer.h>

#import "LyricsFetcherForiPhoneAppDelegate.h"
#import "ChartLyricsLyricsProvider.h"

@implementation LyricsFetcherForiPhoneAppDelegate

@synthesize window;
@synthesize rootViewController;
@synthesize managedObjectContext;

- (void) subscribeToNotifications {
	[[NSNotificationCenter defaultCenter] 
		addObserver:self 
		selector:@selector(currentTrackChanged:) 
		name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification 
		object:nil
	];
}

- (void) unsubscribeFromNotifications {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (TrackInfo*) getCurrentTrackInfo {
	MPMusicPlayerController *player = [MPMusicPlayerController iPodMusicPlayer];
	MPMediaItem *item = [player nowPlayingItem];
	if (item == nil)
		return nil;
		
	return [[[TrackInfo alloc] 
		initWithName: [item valueForProperty:MPMediaItemPropertyTitle]
		artist:		  [item valueForProperty:MPMediaItemPropertyArtist]
		id:			  [item valueForProperty:MPMediaItemPropertyPersistentID]
		lyrics:		  [item valueForProperty:MPMediaItemPropertyLyrics]
	] autorelease];
}

- (void) onCurrentTrackChanged {
	TrackInfo* track = [self getCurrentTrackInfo];
	if (track == nil)
		return;
	
	[rootViewController onCurrentTrackChanged:track];
}

- (void) currentTrackChanged:(NSNotification*)notification {
	[self onCurrentTrackChanged];
}

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
	[self subscribeToNotifications];
	
	NSManagedObjectContext *context = [self managedObjectContext];
	if (context == nil)
		NSLog(@"Failed to create managed object context.");
	
	rootViewController.managedObjectContext = context;
	rootViewController.lyricsProvider = [[ChartLyricsLyricsProvider new] autorelease];
	
	[window addSubview:rootViewController.view];
    [window makeKeyAndVisible];
	
	[self onCurrentTrackChanged];
	
	return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    NSError *error = nil;
    if (_managedObjectContext != nil) {
        if ([_managedObjectContext hasChanges] && ![_managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}
- (void)applicationDidEnterBackground:(UIApplication *)application {}
- (void)applicationWillEnterForeground:(UIApplication *)application {}
- (void)applicationDidBecomeActive:(UIApplication *)application {}

- (void)applicationWillTerminate:(UIApplication *)application {
	[self unsubscribeFromNotifications];
}

- (NSManagedObjectContext*) managedObjectContext {    
    if (_managedObjectContext != nil)
        return _managedObjectContext;
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [NSManagedObjectContext new];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
	
    return _managedObjectContext;
}

- (NSManagedObjectModel*) managedObjectModel {
    if (_managedObjectModel != nil)
        return _managedObjectModel;
	
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"LyricsFetcherForiPhone" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
	
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator*) persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [NSURL fileURLWithPath: 
		[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"LyricsFetcherForiPhone.sqlite"]
	];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [
		[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]
	];
	
	id result = [_persistentStoreCoordinator 
		addPersistentStoreWithType:NSSQLiteStoreType 
		configuration:nil 
		URL:storeURL 
		options:nil 
		error:&error
	];
	
    if (!result) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return _persistentStoreCoordinator;
}

- (NSString*) applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


- (void) applicationDidReceiveMemoryWarning:(UIApplication *)application { }


- (void) dealloc {
    [_managedObjectContext release];
    [_managedObjectModel release];
    [_persistentStoreCoordinator release];
    
    [window release];
	[rootViewController release];
	
    [super dealloc];
}

@end